package com.vip.sys.modular.oshi.service.impl;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.NumberUtil;
import com.vip.sys.modular.oshi.entity.*;
import com.vip.sys.modular.oshi.service.OshiService;
import org.springframework.stereotype.Service;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.util.Util;

import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * @author ASUS
 * @Date 2025/3/28 22:48
 * @Descripition
 */
@Service
public class OshiServiceImpl implements OshiService {
    private static final int OSHI_WAIT_SECOND = 1000;
    SystemInfo si = new SystemInfo();
    HardwareAbstractionLayer hal = si.getHardware();

    @Override
    public Cpu getCpuInfo() {
        //Cpu信息
        long[] prevTicks = hal.getProcessor().getSystemCpuLoadTicks();
        //睡眠1秒
        Util.sleep(OSHI_WAIT_SECOND);
        long[] ticks = hal.getProcessor().getSystemCpuLoadTicks();
        long nice = ticks[CentralProcessor.TickType.NICE.ordinal()] - prevTicks[CentralProcessor.TickType.NICE.ordinal()];
        long irq = ticks[CentralProcessor.TickType.IRQ.ordinal()] - prevTicks[CentralProcessor.TickType.IRQ.ordinal()];
        long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.ordinal()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.ordinal()];
        long steal = ticks[CentralProcessor.TickType.STEAL.ordinal()] - prevTicks[CentralProcessor.TickType.STEAL.ordinal()];
        long cSys = ticks[CentralProcessor.TickType.SYSTEM.ordinal()] - prevTicks[CentralProcessor.TickType.SYSTEM.ordinal()];
        long user = ticks[CentralProcessor.TickType.USER.ordinal()] - prevTicks[CentralProcessor.TickType.USER.ordinal()];
        long iowait = ticks[CentralProcessor.TickType.IOWAIT.ordinal()] - prevTicks[CentralProcessor.TickType.IOWAIT.ordinal()];
        long idle = ticks[CentralProcessor.TickType.IDLE.ordinal()] - prevTicks[CentralProcessor.TickType.IDLE.ordinal()];
        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
        return Cpu.builder()
                .cpuNum(hal.getProcessor().getLogicalProcessorCount())
                .total(totalCpu)
                .sys(cSys)
                .used(user)
                .waits(iowait)
                .free(idle)
                .build();
    }

    @Override
    public Jvm getJvmInfo() {
        Properties props = System.getProperties();
        return Jvm.builder()
                .total(Runtime.getRuntime().totalMemory())
                .max(Runtime.getRuntime().maxMemory())
                .free(Runtime.getRuntime().freeMemory())
                .version(props.getProperty("java.version"))
                .home(props.getProperty("java.home"))
                .build();
    }

    @Override
    public Mem getMemInfo() {
        return Mem.builder()
                .total(hal.getMemory().getTotal())
                .used(hal.getMemory().getTotal()-hal.getMemory().getAvailable())
                .free(hal.getMemory().getAvailable())
                .build();
    }

    @Override
    public Sys getSysInfo() {
        Properties props = System.getProperties();
        return Sys.builder()
                .computerName(NetUtil.getLocalhost().getHostName())
                .computerIp(NetUtil.getLocalhost().getHostAddress())
                .osName(props.getProperty("os.name"))
                .osArch(props.getProperty("os.arch"))
                .userDir(props.getProperty("user.dir"))
                .build();
    }

    @Override
    public List<SysFile> getSysFileInfo() {
        FileSystem fileSystem = si.getOperatingSystem().getFileSystem();
        OSFileStore[] fsArray = fileSystem.getFileStores().toArray(new OSFileStore[0]);
        return Arrays.stream(fsArray)
                .map(fs -> SysFile.builder()
                        .dirName(fs.getMount())
                        .sysTypeName(fs.getType())
                        .typeName(fs.getName())
                        .total(convertFileSize(fs.getTotalSpace()))
                        .free(convertFileSize(fs.getUsableSpace()))
                        .used(convertFileSize(fs.getTotalSpace() - fs.getFreeSpace()))
                        .usage(NumberUtil.round(NumberUtil.mul(fs.getTotalSpace() - fs.getFreeSpace(), fs.getTotalSpace(), 4), 100).doubleValue())
                        .build())
                .collect(Collectors.toList());
    }
    /**
     * 字节转换
     *
     * @param size 字节大小
     * @return 转换后值
     */
    public String convertFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
        if (size >= gb) {
            return String.format("%.1f GB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        } else {
            return String.format("%d B", size);
        }
    }
}
